package com.lc.my_springframework.beans.factory.support;

import com.lc.my_springframework.beans.BeansException;
import com.lc.my_springframework.beans.factory.BeanFactory;
import com.lc.my_springframework.beans.factory.config.BeanDefinition;

public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {
    @Override
    public Object getBean(String beanName) throws BeansException {
        return doGetBean(beanName, null);
    }

    @Override
    public Object getBean(String beanName, Object... args) throws BeansException {
        return doGetBean(beanName, args);
    }

    protected <T> T doGetBean(String name, Object[] args) {
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }
        BeanDefinition bd = getBeanDefinition(name);
        bean = createBean(bd.getBeanName(), bd, args);
        if (bd.isSingleton()) {
            registerSingleton(name, bean);
        }
        return (T) bean;
    }

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args);

    protected abstract BeanDefinition getBeanDefinition(String name);
}
